package com.twu.biblioteca;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Richard
 * Date: 28/01/13
 * Time: 01:00
 * To change this template use File | Settings | File Templates.
 */
public class Menu {
    public String title;
    public List<MenuItem> itemList;
    public InOut inOut;

    public Menu(InOut _inOut) {
        inOut = _inOut;
    }
    public Menu() {}

    public void display() {
        inOut.println(title);
        for (MenuItem item : itemList) {
            inOut.println(item.text);
        }
    }

    public void displayAndRead() {
        this.display();
        this.read();
    }

    public boolean selectItem(int inputValue) {
        if (inputValue < itemList.size() && inputValue >= 0) {
            itemList.get(inputValue).select.Invoke();
            return true;
        }
        else {
            inOut.println("Select a valid option!!");
            return false;
        }
    }

    public void read() {
        boolean valid = false;
        while (!valid) {
            String input = inOut.readNext();
            int inputValue;
            try {
                inputValue = Integer.parseInt(input);
            }
            catch (NumberFormatException e) {
                inputValue = -1;
            }
            valid = this.selectItem(inputValue);
        }
    }
}
